import React, { useEffect } from "react";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { Button, Form } from "@douyinfe/semi-ui";
import { IconEyeOpened, IconPlusCircle } from "@douyinfe/semi-icons";
import { message, Table, Image, Pagination, Modal, Input } from "antd";
const { Search } = Input;

const ChooseCommodity = (props) => {
    const { graphqlFetch, numberFormat } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const { gatewayUrl } = useModel("organization.info");

    const state = useReactive({
        commodities: [],
        loading: false,
        totalCount: 0,
        previewImages: [],
        visible: false,
        visible1: false,
        selectedRowKeys: [],
        selectCommodity: [],
        commodityName: "",
        page: 1,
        pageSize: 20,
        ciUuids: [],
    });

    const loadCommodities = async () => {
        state.loading = true;
        // let data = { notIn: state.ciUuids || [], first: state.pageSize || 20, offset: (state.page - 1) * state.pageSize || 0 };
        // if (state.commodityName) data.ciAlna = state.commodityName;
        // let res = await graphqlFetch({ query: GetCommodityAll, variables: data });
        // if (res?.a?.nodes) state.commodities = res.a.nodes || [];
        // state.totalCount = res?.a?.totalCount || 0;
        state.loading = false;
    };

    useEffect(() => {
        state.ciUuids = props.ciUuids || [];
        loadCommodities();
    }, [props.ciUuids, state.page]);

    const onSearch = async (values) => {};

    const onSubmit = async (values) => {
        state.loading = true;
        let saveData = {
            dpUuid: props.cardItem.dpUuid,
            ciSepr: values.ciSepr,
            ciUuid: state.selectCommodity.ciUuid,
            ciQuat: 1,
        };
        // let res = await graphqlFetch({ query: AddCardCommodity, variables: saveData });
        // if (res) message.success("成功添加商品！");

        state.visible1 = false;
        let notIn = state.ciUuids || [];
        notIn.push(state.selectCommodity.ciUuid);
        state.ciUuids = notIn;
        loadCommodities();
        props.reloadData();
        state.loading = false;
    };

    const columns = [
        {
            title: "商品图片",
            key: "ciPict",
            dataIndex: "ciPict",
            width: 100,
            align: "center",
            render: (_, r, index) =>
                _ && _.length > 0 ? (
                    <Image
                        height={64}
                        preview={{ visible: false }}
                        src={_[0]?.path ? gatewayUrl + "/file/download?filepath=" + _[0].path : null}
                        onClick={() => {
                            state.previewImages = _ || [];
                            state.visible = true;
                        }}
                    />
                ) : (
                    ""
                ),
        },
        { title: "商品全称", dataIndex: "ciAlna", align: "center" },
        { title: "描述", dataIndex: "ciDesc", align: "center", width: 100 },
        { title: "单位", dataIndex: "ciUnit", align: "center", width: 100 },
        { title: "单价", dataIndex: "ciMava", align: "center", width: 100, render: (_, r, index) => (_ ? numberFormat(_, 2) : "") },
        { title: "会员价", dataIndex: "ciMava", align: "center", width: 100, render: (_, r, index) => (_ ? numberFormat(_, 2) : "") },
        { title: "数量", dataIndex: "ciQuat", align: "center", width: 100 },
        {
            title: "操作",
            dataIndex: "operator",
            align: "center",
            width: 60,
            render: (_, record) => (
                <Button
                    icon={<IconPlusCircle />}
                    onClick={() => {
                        state.visible1 = true;
                        state.selectCommodity = record;
                    }}
                />
            ),
        },
    ];

    return (
        <div style={{ padding: 10 }}>
            <Search
                placeholder="请输入套餐名称"
                onSearch={onSearch}
                style={{
                    width: 200,
                }}
            />
            <div style={{ marginTop: 10 }}></div>
            <Table
                loading={state.loading}
                bordered={false}
                size="default"
                pagination={false}
                columns={columns}
                dataSource={[
                    {
                        ciPict: {},
                        ciAlna: "啥也不是",
                        ciDesc: "1231231231231",
                        ciUnit: "个",
                        ciMava: 50,
                        ciQuat: 1,
                    },
                ]}
                rowKey="ciUuid"
                scroll={{ y: 600 }}
            />
            <div style={{ display: "flex", justifyContent: "space-between", height: 48, borderTop: "1px solid #ccc" }}>
                <div></div>
                <div style={{ marginTop: 12 }}>
                    <Pagination
                        total={state.totalCount}
                        showTotal={(total, range) => `当前显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                        pageSize={state.pageSize}
                        current={state.page}
                        showSizeChanger={false}
                        onChange={(page) => (state.page = page)}
                    />
                </div>
            </div>
            <div style={{ display: "none" }}>
                <Image.PreviewGroup preview={{ visible: state.visible, onVisibleChange: (vis) => (state.visible = vis) }}>
                    {state.previewImages?.map((item) => (
                        <Image key={item.path} src={item.path ? gatewayUrl + "/file/download?filepath=" + item.path : null} />
                    ))}
                </Image.PreviewGroup>
            </div>
            <Modal
                title="请设置商品结算价格"
                width={500}
                visible={state.visible1}
                closable={true}
                footer={null}
                getContainer={false}
                style={{ top: 150 }}
                onCancel={() => (state.visible1 = false)}
            >
                <Form labelPosition="left" labelWidth={150} labelAlign="left" key="1" style={{ padding: "20px", width: "100%" }} onSubmit={onSubmit}>
                    <Form.InputNumber field="ciSepr" label="套餐价" trigger="blur" precision={2} rules={[{ required: true, message: "商品售价不能为空" }]} />
                    <div style={{ textAlign: "center" }}>
                        <Button type="primary" theme="solid" htmlType="submit" style={{ width: 120, marginTop: 12, marginRight: 4 }}>
                            提交
                        </Button>
                    </div>
                </Form>
            </Modal>
        </div>
    );
};

export default ChooseCommodity;
